<template>
	<view class="bulletScreen-container" >
		<!-- 弹幕显示区域 -->
		<scroll-view class="bullet-disply" scroll-y="true" :scroll-top="scrollTopRef" v-show="display"
		:class="{'fade-in': display, 'fade-out': !display}">
			<view class="bullets-container">
				<view
				 v-for="(bullet, index) in displayBullets" 
				:key="bullet.id || index"
				class="bullet-item">
				<text :style="bullet.style" class="bullet-bubble">{{ bullet.content }}</text>
				</view>
			</view>
		</scroll-view>
		
		<view class="bullet-component">
			<!-- 弹幕开关 -->
			<uni-icons class="bullet-switch" custom-prefix="iconfont" type="icon-danmu" size="30" color="#E5E5E5" @click="toggleDisplay"></uni-icons>
			<!-- 弹幕输入按钮 -->
			<view class="input-area" v-show="display" :class="{'fade-in': display, 'fade-out': !display}">
				<view class="uni-input" @click="openInputBox">讨论...</view>
				<uni-icons class="expression-icon" custom-prefix="iconfont" type="icon-biaoqing" size="25" color="#A6A6A6"
				></uni-icons>
			</view>
			
			
			
		</view>
	</view>
	<!-- 弹幕输入框 -->
	<view class="input-bar" :style="{ bottom: keyboardHeight + 'rpx' }" v-if="inputBox" >
		<input 
		v-model="inputValue" 
		class="input-box" 
		@focus="onFocus"
		@blur="onBlur"
		placeholder="输入弹幕内容..."
		confirm-type="send"
		@confirm="sendBullet"
		>
		<button class="send-btn" @click="sendBullet">发送</button>
	</view>
</template>

<script setup>
import { ref , onMounted , nextTick , getCurrentInstance , computed , watch } from 'vue';

// 弹幕开关
const display = ref(false)
const toggleDisplay = () => {
	// 切换显示状态
	display.value = !display.value
	
	// 如果显示弹幕，滚动到底部
	if (display.value) {
		nextTick(() => {
			scrollToBottom()
		})
	}
}



// 输入内容
const inputValue = ref('')
// 弹幕列表
const bullets = ref([])
// 发送弹幕
const sendBullet = () =>{
	
	if (!inputValue.value.trim()) return

	 // 创建新弹幕，添加唯一ID和时间戳
	  const newBullet = {
	    id: Date.now(), // 添加唯一ID
	    content: inputValue.value,
	    style: generateBulletStyle(),
	    timestamp: Date.now(), // 添加时间戳
        isNew: true // 标记为新弹幕，用于动画效果
	  }
	  
	  // 添加到弹幕列表
	  bullets.value.push(newBullet)
	  
	  // 滚动到底部
	  nextTick(() => {
		  scrollToBottom();
	    });
	  // 清空输入框
	  inputValue.value = ''
	  
	  openInputBox()
	  
	  // 30秒后自动移除弹幕
	  // setTimeout(() => {
	  //   const index = bullets.value.findIndex(b => b.id === newBullet.id) // 使用ID查找
	  //   if (index !== -1) {
	  //     bullets.value.splice(index, 1)
	  //   }
	  // }, 5000)
}


// 获取当前组件实例
const instance = getCurrentInstance();
// 获取元素dom信息
const getElementsInfo = () => {
	return new Promise((resolve, reject) => {
		if (!instance || !instance.proxy) {
		  reject(new Error('无法获取组件实例'));
		  return;
		}
    
		const query = instance.proxy.createSelectorQuery();
		let scrollViewRect = null;
		let inputBoxRect = null;
    
		// 获取 scroll-view 信息
		query.select('.bullet-disply')
			.boundingClientRect(rect => {
				scrollViewRect = rect;
			});
    
		// 获取 input-box 信息
		query.select('.input-box')
			.boundingClientRect(rect => {
				inputBoxRect = rect;
			});
    
		// 执行查询并返回整合结果
		query.exec(() => {
			resolve({
				scrollView: scrollViewRect,
				inputBox: inputBoxRect
			});
		});
	});
};


// 点击弹出输入框
const inputBox = ref(false)
// const inputRef = ref(null);
const openInputBox = ()=>{
	inputBox.value = !inputBox.value
	// 使用nextTick确保DOM更新后再聚焦
	// console.log(inputRef.value);
    // nextTick(() => {
    //     inputRef.value.focus();
    // });
}

const keyboardHeight = ref(0);
const originalBottom = ref('0px');
// 聚焦时触发（键盘弹出）
const onFocus = (e) => {
  // 监听键盘高度变化（小程序特有）
  uni.onKeyboardHeightChange((res) => {
    keyboardHeight.value = res.height;
    console.log('键盘高度:', res.height);
  });
};
// 失焦时触发（键盘收起）
const onBlur = () => {
  uni.offKeyboardHeightChange();
  keyboardHeight.value = 0;
};

onMounted(() => {
  // getScrollViewElement()
});

// const  screenTop = ref(0)
const scrollTopRef = ref(0)

// 滚动到底部函数
const scrollToBottom = async () => {
	try {
		const { scrollView } = await getElementsInfo();
		if (scrollView && bullets.value.length > 0) {
			// 设置滚动位置为最大值，确保滚动到底部
			nextTick(() => {
				const query = uni.createSelectorQuery().in(instance.proxy);
				query.select('.bullets-container').boundingClientRect();
				query.selectViewport().scrollOffset();
				query.exec((res) => {
					if (res && res[0]) {
						// 计算滚动位置
						scrollTopRef.value = res[0].height > scrollView.height ? 
							res[0].height - scrollView.height : 0;
					}
				});
			});
		}
	} catch (error) {
		console.error('滚动到底部失败:', error);
	}
};

const generateBulletStyle = () => {
  return {
    display: 'inline-block',
    width: 'auto',
    whiteSpace: 'normal',
    wordBreak: 'break-word',
  }
}

const displayBullets = computed(() => {
  return [...bullets.value];
});

// 监听弹幕变化，自动滚动到底部
watch(() => bullets.value.length, () => {
  nextTick(() => {
    scrollToBottom();
  });
});

</script>

<style lang="scss" scoped>
.bulletScreen-container{
	display: flex;
	position: fixed;
	width: 200rpx;
	height: 200rpx;
	bottom: 20rpx;
	left: 35rpx;
	z-index: 10; /* 添加z-index，确保高于wash-hands */
	pointer-events: none; /* 默认不拦截点击事件，穿透到下层元素 */
	.bullet-disply{
		flex: 1;
		width: 100%;
		height: 80%;
		overflow: auto;
		transition: opacity 0.5s ease;
		// border: #2A82E4 solid 1rpx;
		z-index: 10 !important; /* 修改为一致的值，不要使用过高的值 */
		pointer-events: auto; /* 仅当显示时接收点击事件 */
		&:not(.fade-in) {
			pointer-events: none; /* 未显示时不拦截点击事件 */
		}
		.bullets-container{
			width: 100%;
			display: flex;
			flex-direction: column; 
			justify-content: flex-end; /* 内容从底部开始排列 */
			min-height: 100%;
			.bullet-item{
				word-wrap: break-word;
				display: flex; /* 使用flex布局 */
				justify-content: flex-start; /* 左对齐 */
				text-align: left;
				margin: 5rpx 0;
				width: 100%; /* 占满容器宽度 */
				.bullet-bubble{
					display: inline-block;
					padding: 5rpx 10rpx;
					max-width: 80%;
					background-color: rgba(0, 0, 0, 0.5);
					border-radius: 12rpx;
					color: #fff;
					box-sizing: border-box;
					word-break: break-word;
					white-space: normal; /* 允许文本换行 */
					width: auto; /* 自适应宽度 */
					animation: fadeIn 0.5s ease-in; /* 为每个气泡添加淡入动画 */
				}
			}
		}
	}
	
	.bullet-component{
		position: absolute;
		bottom: 0rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 11; /* 确保控制区域在最上方 */
		pointer-events: auto; /* 始终接收点击事件 */
		.bullet-switch{
			margin: 5rpx;
		}
		.input-area{
			display: flex;
			position: relative;
			align-items: center;
			width: 150rpx;
			height: 30rpx;
			background-color: rgba(0, 0, 0, 0.5);
			border-radius: 30rpx;
			transition: opacity 0.5s ease;
			pointer-events: auto; /* 始终接收点击事件 */
			.uni-input{
				width: 100%;
				padding: 10rpx;
				color: #a6a6a6;
				font-size: 14rpx;
			}
			.expression-icon{
				position: absolute;
				right: 12rpx;
			}
		}
		
	}
	
	
}
.input-bar{
	position: fixed;
	width: 90%;
	height: 40rpx;
	margin: 30rpx;
	background-color: #fff;
	display: flex;
	align-items: center;
	border-radius: 10rpx;
	z-index: 15; /* 确保输入框始终在最上层 */
	pointer-events: auto; /* 始终接收点击事件 */
	.input-box{
		margin: 5rpx;
		width: 80%;
		height: 80%;
	}
	.send-btn{
		position: absolute;
		right: 0rpx;
		width: 80rpx;
		height: 100%;
		font-size: 15rpx;
		line-height: 40rpx;
		border-radius: 10rpx;
		color: #fff;
		background-color: #2A82E4;
	}
}

// 添加淡入淡出的过渡效果类
.fade-in {
  opacity: 1;
  transition: opacity 0.5s ease-in;
}

.fade-out {
  opacity: 0;
  transition: opacity 0.5s ease-out;
}

/* 定义气泡淡入动画 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10rpx); }
  to { opacity: 1; transform: translateY(0); }
}
</style>